/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package compressmc;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ding.ning
 */
public class CompressMC {

//    final static String HEADER = "CMPM";
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
	// TODO code application logic here
        if (args.length < 2) {
            throw new RuntimeException("src file, dst file");
        }

        String srcUrl = args[0];
        if (srcUrl.endsWith(File.separator)) {
            srcUrl = srcUrl.substring(0, srcUrl.length()-1);
        }
	
        String dstUrl = args[1];
//        if (s3Prefix.startsWith(File.separator)) {
//            s3Prefix = s3Prefix.substring(1);
//        }
        if (dstUrl.endsWith(File.separator)) {
            dstUrl = dstUrl.substring(0, dstUrl.length()-1);
        }
	try {
	    byte[] fileBuffer = readFile(srcUrl);
	    compress(fileBuffer);
	    export(dstUrl, fileBuffer);
	} catch (IOException ex) {
	    Logger.getLogger(CompressMC.class.getName()).log(Level.SEVERE, null, ex);
	}
	
    }
    
    public static byte[] readFile(String url) throws IOException
    {
        System.out.println("read file, url = " + url);
	
	File file = new File(url);
	try (InputStream is = Files.newInputStream(file.toPath())) {

	    int fileLen = (int) file.length();
	    byte[] buffer = new byte[fileLen];
	    
	    int readLen = is.read(buffer);
//	    int readLen = dis.read(buffer);
	    if(readLen != fileLen)
	    {
		throw new RuntimeException("error in reading source file");
	    }

	    return buffer;
	}
    }
    
    private static void compress(byte[] stream)
    {
        System.out.println("compress ...");
	
	int length = stream.length;
	byte mask = (byte)length;
	
	for(int i = 0; i < length; ++i)
	{
	    stream[i] = (byte)(stream[i] ^ mask);
	}
    }

    public static void export(String dstUrl, byte[] stream) throws IOException
    {
        System.out.println("write file, url = " + dstUrl);
        System.out.println("stream size = " + stream.length);
	
	
        final String fileName = dstUrl;
        try (OutputStream out = Files.newOutputStream(Paths.get(fileName), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE, StandardOpenOption.SYNC)) {
//	    out.write(HEADER.getBytes());
	    out.write(stream.length);
            out.write(stream);
            out.close();
        }
	
	
    }
    
}
